// JavaScript Document for http://www.miushake.fr

	/* William Jautée 
		http://www.seyartdesign.fr
	*/



//Fonction isConnected

var connected = false;

var isConnected = function(){
	return connected;
}

// nb de nouvelles notifications
var NotificationNb = new Class({
	initialize:function(nb){
		this.nb = nb;
		this.nbNotifElement = $('nbNewNotifs');
		this.updateNotificationNbUi();
		this.nbNotifElement.addEvent('click',this.goToNotifPage);	
	},
	goToNotifPage:function(ev){
		ev.stop();
		if (new Hash(HM.getHash().parseQueryString()).get('page') != null && new Hash(HM.getHash().parseQueryString()).get('page') == "monCompte"){
			HM.set('cat','mesnotifs');
		} else {
			HM.set('page','monCompte');
			HM.addEvent('page:changed', pNot = function(v){
				if (v == "monCompte"){
					waitingCatRoom = "mesnotifs";
				}
				HM.removeEvent('page:changed',pNot);
			});
		}
		
	},
	updateNotificationNbUi:function(){
		if (this.nb < 1){
			this.nb = 0;
			this.nbNotifElement.setStyle('display','none');
		} else {
			this.nbNotifElement.setStyle('display','inline');
		}
		this.nbNotifElement.set('text',this.nb);		
	},
	incrementNb:function(){
		this.nb++;
		this.updateNotificationNbUi();	
	},
	decrementNb:function(){
		this.nb--;
		this.updateNotificationNbUi();
	},
	setNb:function(nb){
		this.nb = nb;
		this.updateNotificationNbUi();	
	}
})

var notificationNbInstance;

// vérif session
var checkSession = function(){
	var verifSessionInterval = 0;
	
	// Premier appel maintenant inutile, variable connected mis à jour depuis index.php lors de la vérification de session
/*	var req = new Request({
		method:'get',
		url:'../ajax/ping.php?a=firstCheck',
		evalScripts:true
	});
	// premier appel à ping.php pour mettre à jour la variable connected
	req.send();*/
	
	var reqInterval = new Request({
		method:'get',
		url:'../ajax/ping.php?a=interval',
		evalScripts:true
	});
	$('recommandationui').addEvents({
		// Envoyé par le controleur lors de la connexion
		'connected':function(){
			connected = true;
			clearInterval(verifSessionInterval);
			verifSessionInterval = setInterval(function(){reqInterval.send()},120000);
			console.log('connecté');
			// Rafraichissement bloc coté
			$$('.sidebloc.needAuth').each(function(elt){
				elt.setStyle('display','block');
				updateSideBloc(elt);
			});
		},
		// Envoyé par ping.php lors de la perte de la session
		'sessionlost':function(){
			lightbox($('sessionlost'));
			$('logout').fireEvent('click');
		},
		'disconnected':function(){
			connected = false;
			clearInterval(verifSessionInterval);
			// si page active nécessite une authentification -> renvoit sur accueil
			// A revoir
			var p = new Hash(HM.getHash().parseQueryString()).get('page');
			if (p == "monCompte" || p == "maMiutheque" || p == "espaceAdmin" )
				HM.set('page','accueil');
			// fin A revoir
			$$('.activepage').each(function(elt){
				console.log(elt);
				if (elt.hasClass('authRequired'))
					HM.set('page',"accueil");	
			});
			// Cacher les bloc coté
			$$('.sidebloc.needAuth').each(function(elt){
				elt.setStyle('display','none');
			});
		}
	});	
}

// Authentification
var auth = function(){
	$$('#connect,#inscript').removeEvents('click');
	$$('#connect,#inscript').addEvent('click',function(ev){
		ev.stop();
		// Déclaration des constantes
		var CONNECT_FORM = $('connectform');
		var INSCRIPT_FORM = $('inscriptionForm');
		var FORM_CHOISI = null;
		// On cache les formulaires (afin d'en afficher un ensuite selon le cas)
		$$('#connectInscriptForm > div').setStyle('display','none');
		// Affectation de la constante FORM_CHOISI, selon l'action
		if (this.get('id')=="connect")
			FORM_CHOISI = CONNECT_FORM;
		else 
			FORM_CHOISI = INSCRIPT_FORM;
		// Affichage du lightbox
		FORM_CHOISI.setStyle('display','block');
		lightbox($('connectInscriptForm'));
		// Ajout capteur d'évènement au formulaire
		FORM_CHOISI.getElement('form').removeEvents('submit');
		FORM_CHOISI.getElement('form').addEvent('submit',subm = function(evt){
			evt.stop();
			new Request.HTML({
				url:this.action,
				noCache:true,
				onComplete:function(){
					auth(); // Appel récursif de la fonction auth, quoiqu'il arrive (pour les capteur d'évenements).
				},
				onSuccess: function(responseTree,responseElements,responseHTML,responseJavaScript){
					// traitement de la réponse par la fonction traiteReponse(responseElements)
					traiteReponse(responseElements);
				}
			}).post(this);
			
		});
		
		function traiteReponse(responseElements){
			var msg = FORM_CHOISI == CONNECT_FORM ? "Connexion réussi" : "Inscription réussi";
			responseElements.each(function(element){
				// La réponse de la requête ajax est entre balise "span" avec l'id "response"
				if (element.get('id')=="response"){ 
					
					if (element.get('text')=="ok"){
						$('connectInscriptForm').set('html','');
						new Element('p',{'class':"msglightbox",'text':msg}).inject($('connectInscriptForm'));
						setTimeout(closeLightbox,2000);
					}
					else {
						// Si pb de connexion : on traite les cas de retour d'erreur
						if (FORM_CHOISI == CONNECT_FORM)
							$('rep_connex').set('text',element.get('text'));
					}
				}

				// Cas inscription, le formulaire nous a été retourné : on remplace l'ancient formulaire par le nouveau
				if (element.get('id')==INSCRIPT_FORM.get('id')){
					//INSCRIPT_FORM.set('html','');
					//element.inject(INSCRIPT_FORM);	
					INSCRIPT_FORM.set('html',element.get('html'));
				}
	
			});
			// Dans le cas d'une inscription et que le formulaire nous a été retourné, on remet un capteur d'évenement
			if (document.getElement(INSCRIPT_FORM))
				INSCRIPT_FORM.getElement('form').addEvent('submit',subm);
		}
		
	});	
	
	$$('#logout').removeEvents('click');
	$$('#logout').addEvent('click',function(ev){
		if (ev)
			ev.stop();
		new Request.HTML({method:'get',
			url:this.href,
			update:$('connectInscriptForm'),
			onComplete:function(){
				auth();
			}
		}).send();		
	});
	

}
/* A REVOIR
var MiuBox = new Class({ 
	initialize:function(){
		this.initDefault();
		this.isOpen = false;
		this.lightboxwrapper = $('lightboxwrapper');
		this.lightbox = $('lightbox');
		this.lightboxcontent = $('lightboxcontent');
		this.lightboxcontentstorage = $('lightboxcontentstorage');
		this.fxLightboxClose = new Fx.Tween(lightbox,{
			duration:'short',
			link:'cancel',
			onComplete:function(){
				this.closeMiu();
			}
		});
	},
	initDefault:function(){
		this.elt = null;
		this.reinject = true;
	},
	showMiu:function(elt){
		if (this.isOpen){
			this.closeMiu();	
		}
		$$('.closelightbox').addEvent('click',this.closeMiuEffect.bind(this));
		this.resizeTimer = 0;
		window.addEvent('resize',this.doResize);
		this.lightboxwrapperajust();
		this.isOpen = true;
		this.elt = elt;
		this.elt.inject(this.lightboxcontent);
		this.lightboxwrapper.setStyle('display','block');
		this.lightbox.setStyle('display','block');
	},
	setReinject:function(value){
		this.reinject = value;
	},
	closeMiuEffect:function(ev){
		ev.stop();
		this.lightboxwrapper.setStyle('display','none');
		this.fxLightboxClose.start('opacity',[1, 0]);
		window.removeEvent('resize',this.doResize);	
	},
	closeMiu:function(){
		this.lightbox.setStyle('display','none');
		this.reinject();
		this.lightbox.set('opacity',1);
		$$('.closelightbox').removeEvents('click');
		this.initDefault();
		this.isOpen = false;
	},
	reinject:function(){
		if (this.reinject)
			this.elt.inject(this.lightboxcontentstorage);
		else 
			this.elt.dispose();	
	},
	doResize:function(){
		if (this.resizeTimer)
			clearTimeout(this.resizeTimer);
		this.resizeTimer = setTimeout(this.lightboxwrapperajust.bind(this), 50);	
	},
	lightboxwrapperajust:function(){
		var h = window.getScrollSize().y;
		var posScrollY = window.getScroll().y;
		this.lightboxwrapper.setStyles({'width':window.getSize().x,'height':h});
		this.lightbox.setStyles({'margin-left':(window.getSize().x/2)-(this.lightbox.getSize().x/2),'margin-top':(window.getSize().y/2)-(this.lightbox.getSize().y/2)+posScrollY});	
	}
	
	
});
*/

// Lightbox maison
var lightbox = function(element,ephemeralElement){ 

	var reinject = true;
	
	// ephemeralElement : element crée à la volée en javascript, qui ne doit pas être réinjecté dans le lightboxcontentstorage, mais détruit
	if (ephemeralElement)
		reinject = false;
		
	var isOpen = true;
	var lightboxwrapper = $('lightboxwrapper');
	var lightbox = $('lightbox');
	var lightboxcontent = $('lightboxcontent');
	var lightboxcontentstorage = $('lightboxcontentstorage');
	
	if (lightboxcontent.getFirst('div'))
		lightboxcontent.getFirst('div').inject(lightboxcontentstorage);
		
	lightboxcontent.empty();
		
	element.inject(lightboxcontent);
	
	lightboxwrapper.setStyle('display','block');
	lightbox.setStyle('display','block');
				
	var fxLightboxClose = new Fx.Tween(lightbox,{
		duration:'short',
		link:'cancel',
		onComplete:function(){
			lightbox.setStyle('display','none');
			//lightbox.getElements('input[type=text]').set('value',"");
			//lightbox.getElements('input[type=password]').set('value',"");
			// nettoyage reptext, à revoir :
			//$$('.merreur').set('text','');
			if (reinject)
				element.inject(lightboxcontentstorage);
			else
				element.dispose();
			lightbox.set('opacity',1);
		}
	});
	
	var resizeTimer = 0;
	
	var lightboxwrapperajust = function(){
		/*if ( window.getSize().y < window.getScrollSize().y)
			var h = window.getSize().y;
		else*/ 
		var h = window.getScrollSize().y;
		var posScrollY = window.getScroll().y;
		lightboxwrapper.setStyles({'width':window.getSize().x,'height':h});
		lightbox.setStyles({'margin-left':(window.getSize().x/2)-(lightbox.getSize().x/2),'margin-top':(window.getSize().y/2)-(lightbox.getSize().y/2)+posScrollY});
	}
	
	
	var doResize = function(){
		if (resizeTimer)
			clearTimeout(resizeTimer);
	
		resizeTimer = setTimeout(lightboxwrapperajust, 50);
	}
	
	window.addEvent('resize',doResize);
	
	lightboxwrapperajust();
	
	$$('.closelightbox').addEvent('click',closeLightbox = function(){
		lightboxwrapper.setStyle('display','none');
		fxLightboxClose.start('opacity',[1, 0]);
		window.removeEvent('resize',doResize);	
	});
}

// Slide upload avatar
var avatarUploadInit = function() {
	
	var formDiv = $('formupload');
	var text = formDiv.getElement('p').get('text');
	var FxUpload = new Fx.Slide(formDiv, {
		duration:500,
		mode: 'horizontal',
		transition: Fx.Transitions.Pow.easeOut
	});
	FxUpload.hide();

	$$('.modifAvatar').addEvent('click',function(ev){
		ev.stop();
		FxUpload.toggle();
		if (FxUpload.open)
			resetUpload();
	});

	$$('.supprAvatar').addEvent('click',function(ev){
		ev.stop();
		var update = $('userprofilavatar');
		var req = new Request.HTML({
			method:'get',
			update:update,
				url:'index.php?a=delAvatar',
				onRequest:function(){
					update.fade("out");
				},
				onComplete: function(){
					update.fade("in");
				}						   
			});
			req.send();

	});
	formDiv.addEvent('submit',function(ev){
		this.getElement('p').set('text','Upload en cours...');
		this.getElement('form').setStyle('display','none');
	});
	$$('.annulerUpload').addEvent('click',resetUpload = function(ev){
		if (ev)
			ev.stop();
		FxUpload.slideOut();
		formDiv.getElement('p').set('text',text);
		formDiv.getElement('form').setStyle('display','block');
		formDiv.getElement('input[type=file]').set('value','');
	});
	
}

/* Traitement résultat de l'upload image (appel depuis l'iframe caché) */
function resultUpload(etat) {
	var update = $('userprofilavatar');
	var form = $('formupload');
	if (etat == 1){
		var req = new Request.HTML({
			method:'get',
			update: update,
			noCache:true,
			url:'index.php?a=refreshAvatar',
			onRequest:function(){
				update.fade("out");
			},
			onComplete: function(){
				update.fade("in");
				resetUpload();
			}
		});
		req.send();

	} else {
		form.getElement('form').setStyle('display','block');
		form.getElement('p').set('text','Une erreur s\'est produite');
	}
}

// Recherche Utilisateur
var userSearch = function(){

	var form = $('friendsearchform').getElement('form');
	var update = form.getParent('section').getElement('.containerBlocP');
	form.addEvent('submit',function(ev){
		ev.stop();
		new Request.HTML({
			method:'get',
			update: update,
			//url:'index.php?a=rechercher',
			url : form.action,
			data:'user=1&cle='+form.getElement('.rech input').get('value'),
			onRequest:function(){
				loader.makeAppear(false);
			},
			onSuccess: function(responseTree,responseElements,responseHTML,responseJavaScript){
				loader.makeDisappear();
				addEventBlocP();
			}
		}).send();
	});
	
	
}

// Tips Diagramme Venn

var initializeVennTips = function(){
	

	$$('.venndiag').each(function(element,index) {
		if (element.get('title')){
    		var content = element.get('title').split('::');
    		element.store('tip:title', content[0]);
    		element.store('tip:text', content[1]);
		}
  	});

	var tipsVenn = new Tips('.venndiag');

}

// requete ajout amis
var addFriend = function(ev){
	ev.stop();
	if (!accessVerification(this))
		return;
	this.removeEvents('click');
	var elClicked = this;
	var parent;
	if (this.getParent('.userL,.userP'))
		parent = this.getParent('.userL,.userP');
	else
		return;
	var id_user = parent.getElement('input.idUser').get('value');
	new Request.HTML({
		method:'get',
		url:'index.php?a=addFriend',
		data:'id_user='+id_user,
		onSuccess: function(responseTree,responseElements,responseHTML,responseJavaScript){
			var tmp = new Element('div',{'html':responseHTML});
			lightbox(tmp.getElement('.ephemeralLightboxResponse'),true);
			setTimeout(closeLightbox,2000);
			if (! parent.hasClass('notificationL')){
				tmp.getElement('.addFriendInteracState').replaces(ev.target);
				$$('.notificationL').each(function(l){
					if (l.getElement('input.idUser').get('value') == id_user){
						makeNotificationDisappear(l.getElement('.acceptFriend'));
					}
				});
			} else { // si le clic provient d'une notification
				$$('.userL').each(function(l){
					if (! l.hasClass('notificationL') && l.getElement('input.idUser').get('value') == id_user){
						l.getElement('.addfriendbutton').dispose();	
					}
				});
				makeNotificationDisappear(elClicked);	
			}
			// rafraichissement de "mes amies" si on se trouve dans la page des amis
			if ($('blocMyFriendS')){
				console.log("test si blocMyFriends");
				getBlocP($('blocMyFriendS').getFirst(),"?a=getCat&cat=mesamis&typeP=bloc");			
			}
			// Rafraichissement bloc coté
			$$('.sidebloc.updateOnAddFriend').each(function(elt){
				updateSideBloc(elt);
			});
		}
	}).send();
}

// Evennements d'interactions entre utilisateurs

var addEventInteracUser = function(){
	// Page profil
	$$('.username').removeEvents('click');
	$$('.username').addEvent('click',function(ev){
		ev.stop();
		var id_user = this.getParent('.userL').getElement('input.idUser').get('value');
		HM.set('user',id_user);
	});
	
	// ajout d'amis
	$$('.addfriendbutton').removeEvents('click');
	$$('.addfriendbutton').addEvent('click', addFriend);
	// ajout watchlist
	$$('.addwatchlistbutton').removeEvents('click');
	$$('.addwatchlistbutton').addEvent('click',function(ev){
		ev.stop();
		if (! accessVerification(this))
			return;
		this.removeEvents('click');
		var elClicked = this;
		var parent;
		if (this.getParent('.userL,.userP'))
			parent = this.getParent('.userL,.userP');
		else
			return;
		var id_user = parent.getElement('input.idUser').get('value');
		new Request.HTML({
			method:'get',
			url:'index.php?a=addFollower',
			data:'id_user='+id_user,
			onSuccess: function(responseTree,responseElements,responseHTML,responseJavaScript){
				var tmp = new Element('div',{'html':responseHTML});
				tmp.getElement('.addFollowerInteracState').replaces(ev.target);
				lightbox(tmp.getElement('.ephemeralLightboxResponse'),true);
				setTimeout(closeLightbox,2000);
				// rafraichissement de "ma watchList" si on se trouve dans la page des amis
				if ($('blocMyWatchList')){
					console.log("test si blocMyFriends");
					getBlocP($('blocMyWatchList').getFirst(),"?a=getCat&cat=mawatchlist&typeP=bloc");			
				}
				// Rafraichissement bloc coté
				$$('.sidebloc.updateOnAddWatchList').each(function(elt){
					updateSideBloc(elt.getElement('.sideblocUpdateContainer').get('id'));
				});
			}
		}).send();	
	});
}

// Evenements réponses aux notifications

var addEventNotifications = function(){
	
	var id_notification;
	var newNotifState;
	
	// Doit correspondre au fichier config.php
	var NOTIFICATION_NEW = 0; // nouvelle notification
	var NOTIFICATION_HID = 1; // "ignorer" une demande d'ami par exemple
 	var NOTIFICATION_DEL = 2;
	
	$$('.acceptFriend').removeEvents('click');

	$$('.acceptFriend').addEvent('click', addFriend);

	$$('.ignoreFriend').removeEvents('click');
	$$('.ignoreFriend').addEvent('click',function(ev){
		ev.stop();
		
		id_notification = this.getParent('.notificationL').getElement('input.idNotification').get('value');	
		newNotifState = NOTIFICATION_HID;
		notificationReq(this);
	});
	$$('.delNotification').removeEvents('click');
	$$('.delNotification').addEvent('click',function(ev){
		ev.stop();
		id_notification = this.getParent('.notificationL').getElement('input.idNotification').get('value');	
		newNotifState = NOTIFICATION_DEL;
		notificationReq(this);
	});
	
	var notificationReq = function(elTarget){
		new Request.HTML({
			method:'get',
			url:'index.php?a=modifyNotification',
			data:'id_notification='+id_notification+'&state_target='+newNotifState,
			onSuccess: function(responseTree,responseElements,responseHTML,responseJavaScript){
				makeNotificationDisappear(elTarget);
			}
		}).send();
	}

}

// Fait disparaitre la notification

var makeNotificationDisappear = function(elTarget){
	notificationNbInstance.decrementNb();
	var elFx;
	elTarget.getParent('.notificationL').getElements('a').removeEvents('click');
	elTarget.getParent('.notificationL').getElements('a').addEvent('click',function(ev){ev.stop()});
	if (elTarget.getParent('.notificationcontainer') && elTarget.getParent('.notificationcontainer').getElements('.notificationL').length <=1){
		elFx = elTarget.getParent('.notificationcontainer');
	} else {
		elFx = elTarget.getParent('.notificationL');	
	}
	new Fx.Tween(elFx, {property: 'opacity',onComplete:function(){elFx.dispose()}}).start([1,0]);
}

// SetStatus

var addEventSetUserStatus = function(){
	$$('.setStatus').removeEvents('click');
	$$('.setStatus').addEvent('click',function(ev){
		ev.stop();
		if (this.getParent('.userL,.userP'))
			parent = this.getParent('.userL,.userP');
		else
			return;
		var update = parent.getElement('.moderateinteraction');
		var id_user = parent.getElement('input.idUser').get('value');
		new Request.HTML({	
			method:'get',
			url: this.href,
			data: 'id_user='+id_user,
			update: update,
			onSuccess: function(responseTree,responseElements,responseHTML,responseJavaScript){
				addEventSetUserStatus();
			}
		}).send();
	});
	
}